﻿using AutoMapper;
using MediatR;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.User;
using System.Transactions;
using Microsoft.Extensions.Logging;
using RBAC.Domain.RBAC;

namespace RBAC.Write.Api.Application.Handler.User
{
    public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, APIResult<int>>
    {
        private readonly IBaseRepository<UserModel> userRepository;
        private readonly ILogger<UpdateUserHandler> logger;
        private readonly IMapper mapper;
        private readonly IBaseRepository<UserRoleModel> userRoleRepository;

        public UpdateUserHandler(IBaseRepository<UserModel> userRepository, ILogger<UpdateUserHandler> logger, IMapper mapper, IBaseRepository<UserRoleModel> userRoleRepository)
        {
            this.userRepository = userRepository;
            this.logger = logger;
            this.mapper = mapper;
            this.userRoleRepository = userRoleRepository;
        }
        
        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            
            try
            {
                logger.LogInformation("开始更新用户，用户ID: {UserId}", request.Id);
                
                // 1. 使用Dapper查询用户
                var user = userRepository.GetFirstOrDefault("Id = @Id AND IsDeleted = false", new { Id = request.Id });
                if (user == null)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "用户不存在或已被删除";
                    logger.LogWarning("用户不存在或已被删除，ID: {UserId}", request.Id);
                    return Task.FromResult(res);
                }
                
                logger.LogInformation("找到用户: {UserName} (ID: {UserId})", user.UserName, user.Id);
                
                using (TransactionScope tran = new TransactionScope())
                {
                    try
                    {
                        // 2. 软删除现有的用户角色关联
                        var existingUserRoles = userRoleRepository.GetAll("UserId = @UserId AND IsDeleted = false", new { UserId = request.Id });
                        logger.LogInformation("找到 {UserRoleCount} 个现有用户角色关联", existingUserRoles.Count);
                        
                        foreach (var userRole in existingUserRoles)
                        {
                            userRole.IsDeleted = true;
                            var updateResult = userRoleRepository.Update(userRole);
                            logger.LogInformation("软删除用户角色关联: UserId={UserId}, RoleId={RoleId}, 结果={Result}", 
                                userRole.UserId, userRole.RoleId, updateResult);
                        }
                        
                        // 3. 更新用户基本信息
                        var updatedUser = mapper.Map(request, user);
                        updatedUser.CreateTime = user.CreateTime; // 保持原始创建时间
                        updatedUser.IsDeleted = false;
                        
                        var userUpdateResult = userRepository.Update(updatedUser);
                        logger.LogInformation("用户基本信息更新结果: {Result}", userUpdateResult);
                        
                        // 4. 创建新的用户角色关联
                        if (request.RoleId != null && request.RoleId.Any())
                        {
                            logger.LogInformation("开始创建新的用户角色关联，角色数量: {RoleCount}", request.RoleId.Count());
                            
                            foreach (var roleId in request.RoleId)
                            {
                                var newUserRole = new UserRoleModel
                                {
                                    UserId = request.Id,
                                    RoleId = roleId,
                                    IsDeleted = false,
                                    CreateTime = DateTime.Now
                                };
                                
                                var createResult = userRoleRepository.Create(newUserRole);
                                logger.LogInformation("创建用户角色关联: UserId={UserId}, RoleId={RoleId}, 结果={Result}", 
                                    request.Id, roleId, createResult);
                            }
                        }
                        else
                        {
                            logger.LogInformation("没有指定角色ID，跳过用户角色关联创建");
                        }
                        
                        tran.Complete();
                        
                        res.Code = APIEnums.Success;
                        res.Data = userUpdateResult;
                        res.Msg = "用户更新成功";
                        
                        logger.LogInformation("用户 {UserName} (ID: {UserId}) 更新完成", updatedUser.UserName, updatedUser.Id);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "更新用户过程中发生错误: {Message}", ex.Message);
                        res.Code = APIEnums.Error;
                        res.Msg = "更新用户失败";
                        res.Data = 0;
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                res.Code = APIEnums.Error;
                res.Msg = "更新用户失败";
                logger.LogError(ex, "更新用户失败，用户ID: {UserId}, 错误: {Message}", request.Id, ex.Message);
            }

            return Task.FromResult(res);
        }
    }
}
